package com.net.xpay.backend.scheduler;

import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.SubTaskInfo;
import com.alipay.api.response.AlipayOpenSpIsvSignauthQueryResponse;
import com.google.common.base.Strings;
import com.net.common.dao.Page;
import com.net.common.exception.BusinessException;
import com.net.common.util.SerializationUtil;
import com.net.xpay.alipay.PoseidonAlipayClient;
import com.net.xpay.common.domain.AlipayUserSignAuthRecord;
import com.net.xpay.common.enums.user.AlipayUserSignAuthRecordStatus;
import com.net.xpay.common.helper.NoticeHelper;
import com.net.xpay.common.manager.AlipayUserSignAuthRecordManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自动付定时任务
 */
@Slf4j
@Component
public class SignAuthScheduler {


    @Autowired
    private AlipayUserSignAuthRecordManager alipayUserSignAuthRecordManager;

    @Autowired
    private PoseidonAlipayClient xpayAlipayClient;

    @Autowired
    private NoticeHelper noticeHelper;

    /**
     * 检查签约结果
     */
    @Scheduled(cron = "0 */5 * * * *")
    public void checkSignAuth() {
        AlipayUserSignAuthRecord condition = new AlipayUserSignAuthRecord();
        condition.setStatus(AlipayUserSignAuthRecordStatus.INIT);
        Page page = new Page(100L, 0L);

        List<AlipayUserSignAuthRecord> records = alipayUserSignAuthRecordManager.listWithPage(condition, page);
        log.info("checkSignAuth records size={}", records.size());
        if (records.size() == 0) {
            return;
        }
        for (AlipayUserSignAuthRecord record : records) {
            if (Strings.isNullOrEmpty(record.getBizNo())) {
                continue;
            }
            try {
                AlipayOpenSpIsvSignauthQueryResponse resp = xpayAlipayClient.queryAlipayOpenSpIsvSignauth(record.getBizNo());
                log.info("checkSignAuth resp |alipayNickName={}| resp={}", record.getAlipayNickName(), SerializationUtil.obj2String(resp));
                if (!resp.isSuccess()) {
                    throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, resp.getSubCode());
                }
                record = alipayUserSignAuthRecordManager.getById(record.getId());
                if (resp.getStatus().equals(AlipayUserSignAuthRecordStatus.FAILURE.getValue())) {
                    record.setStatus(AlipayUserSignAuthRecordStatus.FAILURE);
                    if (resp.getTaskInfos() != null) {
                        for (SubTaskInfo info : resp.getTaskInfos()) {
                            if ("SIGN_TASK".equals(info.getType()) && "FAILURE".equals(info.getStatus())) {
                                record.setSignFailureReason(info.getExecuteResult());
                                break;
                            }
                        }
                    }
                    alipayUserSignAuthRecordManager.update(record);
                } else if (resp.getStatus().equals(AlipayUserSignAuthRecordStatus.FINISH.getValue())){
                    record.setStatus(AlipayUserSignAuthRecordStatus.FINISH);
                    alipayUserSignAuthRecordManager.update(record);
                }
                if (record.getSignSubmitTime().isBefore(LocalDateTime.now().minusDays(1L))) {
                    //一天了还没出结果报警
                    log.info("checkSignAuth timeout |alipayNickName={}| resp={}", record.getAlipayNickName(), SerializationUtil.obj2String(resp));
                    noticeHelper.sendSystemMonitorNotice("签约授权一体化任务超时未审核：" + record.getId(), "text");
                }
                if (record.getSignSubmitTime().isBefore(LocalDateTime.now().minusDays(1L))) {
                    //超时1天直接设置为失败
                    record.setStatus(AlipayUserSignAuthRecordStatus.FAILURE);
                    record.setSignEndTime(LocalDateTime.now());
                    record.setIsAuditTimeout(1);
                    alipayUserSignAuthRecordManager.update(record);
                }
            } catch (AlipayApiException e) {
                log.warn("checkSignAuth error|id={}", record.getId(), e);
            }
        }
    }


}
